import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
// import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  Checkbox,
  // InputNumber,
  // DatePicker,
  // Tooltip,
  // Modal,
  // message,
  // Badge,
  Divider,
  // Popconfirm,
  BackTop,
  message,
  notification,
} from 'antd';
import moment from 'moment';
import { isInvalid, getRandomColor, searchFromList, refitCommonData } from '../../utils/tools';
import StandardTableCustom from '../../customComponents/StandardTableCustom';
import PageHeaderWrapperCustom from '../../customComponents/PageHeaderWrapperCustom';
import Ellipsis from '../../components/Ellipsis';

import styles from './List.less';

const FormItem = Form.Item;
// const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ product, global, loading }) => ({
  product,
  global,
  loading: loading.models.product,
}))
@Form.create()
class Standard extends PureComponent {
  isMountedFlag = false;

  state = {
    dataLoading: true,
    processing: false,
    formValues: {},
    customData: {
      count: 0,
      list: [],
      pagination: {},
    },
    pageNo: 1,
    pageSize: 10,
    selectedDataTableDataRows: [],
  };

  componentDidMount() {
    this.isMountedFlag = true;
    const { pageNo, pageSize } = this.state;

    this.loadData({ pageNo, pageSize });
  }

  componentWillUnmount() {
    this.isMountedFlag = false;
  }

  cityList = () => {
    const { global } = this.props;
    return refitCommonData(global.cityList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getCityName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.cityList());
    return item == null ? '未知' : item.name;
  };

  brandList = () => {
    const { global } = this.props;
    return refitCommonData(global.brandList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getBrandName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.brandList());
    return item == null ? '未知' : item.name;
  };

  buyTypeList = () => {
    const { global } = this.props;
    return refitCommonData(global.buyTypeList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getBuyTypeName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.buyTypeList());
    return item == null ? '未知' : item.name;
  };

  rankList = () => {
    const { global } = this.props;
    return refitCommonData(global.rankList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getRankName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.rankList());
    return item == null ? '未知' : item.name;
  };

  productStatusList = () => {
    const { global } = this.props;
    return refitCommonData(global.productStatusList, {
      key: -10000,
      name: '不限',
      flag: -10000,
    });
  };

  getProductStatusName = (v, defaultValue = '') => {
    if (isInvalid(v)) {
      return defaultValue;
    }

    const item = searchFromList('flag', v, this.productStatusList());
    return item == null ? '未知' : item.name;
  };

  loadData = params => {
    const { dispatch } = this.props;

    const submitData = params;
    submitData.nowpageindex = submitData.pageNo;
    submitData.pagesize = submitData.pageSize;

    delete submitData.pageNo;
    delete submitData.pageSize;

    this.setState({ dataLoading: true });

    dispatch({
      type: 'product/list',
      payload: submitData,
    }).then(() => {
      if (this.isMountedFlag) {
        const {
          product: { data },
        } = this.props;

        this.setState({ customData: data, dataLoading: false });
      }
    });
  };

  handleSelectRows = rows => {
    // const list = [];
    // rows.forEach(o => {
    //   list.push(`${o.name}|${o.dataEntityType}`);
    // });
    // const v = list.join();
    // this.setState({
    //   tableList: v,
    // });

    this.setState({
      selectedDataTableDataRows: rows,
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { formValues } = this.state;
    // console.dir(pagination);
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.loadData(params);
  };

  handleFormReset = () => {
    const { form } = this.props;
    const { pageSize } = this.state;

    form.resetFields();
    this.setState({
      formValues: {},
    });

    this.loadData({ pageNo: 1, pageSize });
  };

  refreshGrid = pageNo => {
    const { customData } = this.state;
    const { pagination } = customData;

    const params = {
      pageNo: (pageNo || 1) <= 1 ? 1 : pageNo,
      pageSize: pagination.pageSize,
    };

    this.loadData(params);
  };

  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      this.loadData({
        ...values,
        pageNo: 1,
        pageSize,
      });
    });
  };

  deleteItem = record => {
    const { dispatch } = this.props;

    this.setState({ processing: true });

    dispatch({
      type: 'product/remove',
      payload: {
        productsId: record.productsId,
      },
    }).then(() => {
      const {
        product: { data },
      } = this.props;
      const { code, message: messageText } = data;
      if (code === 200) {
        notification.success({
          placement: 'bottomRight',
          message: '操作结果',
          description: '数据已经删除成功，请进行后续操作。',
        });

        this.setState({ processing: false }, () => {
          const { customData } = this.state;
          const { pagination } = customData;
          const { current } = pagination;
          this.refreshGrid(current);
        });
      } else {
        notification.error({
          placement: 'bottomRight',
          message: '操作结果',
          description: messageText,
        });
      }
    });
  };

  setRecommend = (e, record) => {
    const { dispatch } = this.props;
    const {
      target: { checked },
    } = e;

    this.setState({ processing: true });

    dispatch({
      type: 'product/setRecommend',
      payload: {
        productId: record.intproductid,
        select: checked ? 1 : 0,
      },
    }).then(() => {
      const {
        product: { data },
      } = this.props;

      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '推荐设置操作结果',
            description: `${record.chvtitle}${
              (record.chvspec || '') === '' ? '' : `(${record.chvspec})`
            } 已${checked ? '设为推荐' : '取消推荐设置'}`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setNew = (e, record) => {
    const { dispatch } = this.props;
    const {
      target: { checked },
    } = e;

    this.setState({ processing: true });

    dispatch({
      type: 'product/setNew',
      payload: {
        productId: record.intproductid,
        select: checked ? 1 : 0,
      },
    }).then(() => {
      const {
        product: { data },
      } = this.props;
      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '新品设置操作结果',
            description: `${record.chvtitle}${
              (record.chvspec || '') === '' ? '' : `(${record.chvspec})`
            } 已${checked ? '设为新品' : '取消新品设置'}`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  setGift = (e, record) => {
    const { dispatch } = this.props;
    const {
      target: { checked },
    } = e;

    this.setState({ processing: true });

    dispatch({
      type: 'product/setGift',
      payload: {
        productId: record.intproductid,
        select: checked ? 1 : 0,
      },
    }).then(() => {
      const {
        product: { data },
      } = this.props;
      const { code, message: messageText } = data;
      if (code === 200) {
        setTimeout(() => {
          notification.success({
            placement: 'bottomRight',
            message: '礼品设置操作结果',
            description: `${record.chvtitle}${
              (record.chvspec || '') === '' ? '' : `(${record.chvspec})`
            } 已${checked ? '设为礼品' : '取消礼品设置'}`,
          });
        }, 500);
      } else {
        setTimeout(() => {
          notification.error({
            placement: 'bottomRight',
            message: '操作结果',
            description: messageText,
          });
        }, 500);
      }

      this.setState({ processing: false });
    });
  };

  cancelDelete = () => {
    message.info('已取消删除操作。');
  };

  goToEdit = record => {
    const { dispatch } = this.props;
    const { intproductid } = record;
    const location = {
      // pathname: `/product/supervise/edit/load/${intproductid}/basicInfo`,
      pathname: `/product/edit/load/${intproductid}/basicInfo`,
    };
    dispatch(routerRedux.push(location));
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    const { dataLoading } = this.state;

    const cityData = this.cityList();
    const cityOption = [];

    cityData.forEach(item => {
      const { name, flag } = item;
      cityOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const rankData = this.rankList();
    const rankOption = [];

    rankData.forEach(item => {
      const { name, flag } = item;
      rankOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const brandData = this.brandList();
    const brandOption = [];

    brandData.forEach(item => {
      const { name, flag } = item;
      brandOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    const buyTypeData = this.buyTypeList();
    const buyTypeOption = [];

    buyTypeData.forEach(item => {
      const { name, flag } = item;
      buyTypeOption.push(
        <Select.Option key={flag} value={flag}>
          {name}
        </Select.Option>
      );
    });

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="城市">
              {getFieldDecorator('city', {
                rules: [{ required: false, message: '请选择城市!' }],
                initialValue: cityData[0].flag,
              })(
                <Select placeholder="请选择城市" style={{ width: '100%' }}>
                  {cityOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="编号">
              {getFieldDecorator('serialNumber')(<Input placeholder="请输入商品编号" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="标题">
              {getFieldDecorator('title')(<Input placeholder="请输入商品标题" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="类型">
              {getFieldDecorator('rank', {
                rules: [{ required: false, message: '请选择商品类型!' }],
                initialValue: rankData[0].flag,
              })(
                <Select placeholder="请选择商品类型" style={{ width: '100%' }}>
                  {rankOption}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }} justify="end">
          <Col md={6} sm={24}>
            <FormItem label="渠道">
              {getFieldDecorator('buyType', {
                rules: [{ required: false, message: '请选择销售渠道!' }],
                initialValue: buyTypeData[0].flag,
              })(
                <Select placeholder="请选择销售渠道" style={{ width: '100%' }}>
                  {buyTypeOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="品牌">
              {getFieldDecorator('brand', {
                rules: [{ required: false, message: '请选择商品类型!' }],
                initialValue: brandData[0].flag,
              })(
                <Select placeholder="请选择商品类型" style={{ width: '100%' }}>
                  {brandOption}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={12} sm={24}>
            <span className={styles.submitButtons}>
              <Button disabled={dataLoading} type="primary" icon="search" htmlType="submit">
                查询
              </Button>
              <Button
                disabled={dataLoading}
                style={{ marginLeft: 8 }}
                icon="reload"
                onClick={this.handleFormReset}
              >
                重置
              </Button>
              <Divider type="vertical" />
              <Button
                disabled={dataLoading}
                type="primary"
                icon="plus"
                onClick={this.showAddNewModal}
              >
                新增产品
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { loading } = this.props;
    const { customData, selectedDataTableDataRows, dataLoading, processing } = this.state;
    const columns = [
      {
        title: '编号',
        dataIndex: 'intproductid',
        width: 80,
        align: 'center',
      },
      {
        title: '城市',
        dataIndex: 'intcityid',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {this.getCityName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '商品货号',
        dataIndex: 'chvno',
        width: 100,
        align: 'center',
      },
      {
        title: '所属分类',
        dataIndex: 'intrankid',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val),
              }}
              tooltip
              lines={1}
            >
              {this.getRankName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '商品名称',
        dataIndex: 'chvtitle',
        align: 'left',
        render: (val, record) => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {val}
              {(record.chvspec || '') === '' ? '' : `(${record.chvspec})`}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '推荐',
        dataIndex: 'intRecommend',
        width: 60,
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <Checkbox
              onChange={e => {
                this.setRecommend(e, record);
              }}
            />
          </Fragment>
        ),
      },
      {
        title: '新品',
        dataIndex: 'intNew',
        width: 60,
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <Checkbox
              onChange={e => {
                this.setNew(e, record);
              }}
            />
          </Fragment>
        ),
      },
      {
        title: '礼品',
        dataIndex: 'intGift',
        width: 60,
        align: 'center',
        render: (val, record) => (
          <Fragment>
            <Checkbox
              onChange={e => {
                this.setGift(e, record);
              }}
            />
          </Fragment>
        ),
      },
      {
        title: '进货价格',
        dataIndex: 'moncostprice',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis className={styles.price} tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '服务站价格',
        dataIndex: 'monstockprice',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis className={styles.price} tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '销售价格',
        dataIndex: 'monsaleprice',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis className={styles.price} tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '市场价格',
        dataIndex: 'monexpressprice',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis className={styles.price} tooltip lines={1}>
              ￥{val}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '状态',
        dataIndex: 'intstate',
        width: 120,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis
              style={{
                color: getRandomColor(val + 14),
              }}
              tooltip
              lines={1}
            >
              {this.getProductStatusName(val, '--')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '销售渠道',
        dataIndex: 'intbuytype',
        width: 100,
        align: 'center',
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {this.getBuyTypeName(val)}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '添加时间',
        dataIndex: 'dtmintime',
        width: 120,
        align: 'center',
        sorter: false,
        render: val => (
          <Fragment>
            <Ellipsis tooltip lines={1}>
              {(val || '') === ''
                ? '--'
                : moment(new Date(val.replace('/', '-'))).format('YYYY-MM-DD')}
            </Ellipsis>
          </Fragment>
        ),
      },
      {
        title: '操作',
        width: 106,
        fixed: 'right',
        align: 'center',
        render: (text, record) => (
          <Fragment>
            <Dropdown.Button
              size="small"
              onClick={() => this.goToEdit(record)}
              overlay={
                <Menu onClick={e => this.handleMenuClick(e, record)}>
                  <Menu.Item key="1">
                    <Icon type="setting" />
                    数据
                  </Menu.Item>
                  <Menu.Item key="2">
                    <Icon type="setting" />
                    下架
                  </Menu.Item>
                  {/* <Menu.Item key="2">
                    <Icon type={record.status === 2 ? 'minus-circle' : 'check-circle'} />
                    {record.status === 2 ? '禁用' : '启用'}
                  </Menu.Item> */}
                </Menu>
              }
            >
              <Icon type="edit" />
              修改
            </Dropdown.Button>
          </Fragment>
        ),
      },
      // {
      //   title: '操作',
      //   width: 156,
      //   align: 'center',
      //   fixed: 'right',
      //   render: (text, record) => (
      //     <Fragment>
      //       <a onClick={() => this.goToEdit(record)} className={styles.actionButton}>
      //         <Icon type="edit" className={styles.editButton} />
      //         编辑
      //       </a>
      //       <Popconfirm
      //         placement="topRight"
      //         title="此操作将同步删除设定了此品牌的商品的品牌信息，确定删除吗？"
      //         onConfirm={() => this.deleteItem(record)}
      //         onCancel={this.cancelDelete}
      //         okText="确定"
      //         cancelText="取消"
      //       >
      //         <a className={styles.actionButton}>
      //           <Icon type="delete" className={styles.editButton} />
      //           删除
      //         </a>
      //       </Popconfirm>
      //     </Fragment>
      //   ),
      // },
    ];

    return (
      <PageHeaderWrapperCustom title="商品列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <StandardTableCustom
              loading={dataLoading || processing || loading}
              data={customData}
              selectedRows={selectedDataTableDataRows}
              columns={columns}
              scroll={{ x: 1700 }}
              // expandedRowRender={record => (
              //   <div>
              //     <p>
              //       <span className="bold">商品名称：</span>
              //       <span>{`${record.name}（ 编码：${record.customCode || '无'} ）`}</span>
              //     </p>
              //     <p>
              //       <span className="bold">简介描述：</span>
              //       <span>{record.description}</span>
              //     </p>
              //     <Divider />
              //     <p>
              //       <span className="bold">其他信息：</span>
              //       <span>{`发布于 ${record.dtmintime}，最后更新于 ${record.updateTime}。`}</span>
              //     </p>
              //   </div>
              // )}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <BackTop />
      </PageHeaderWrapperCustom>
    );
  }
}

export default Standard;
